//
//  WriteEmailView.m
//  OASystem
//
//  Created by macos on 14-4-17.
//  Copyright (c) 2014年 macos. All rights reserved.
//

#import "WriteEmailView.h"

@interface WriteEmailView ()

@end

@implementation WriteEmailView
@synthesize draftDic;
@synthesize boolDraft;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        if(!draftDic)
            draftDic = [[NSArray alloc] init];
    }
    return self;
}

//返回上一级
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNavi
{
    //初始化UINavigation
    self.navigationItem.titleView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.text = @"写邮件";
    titleLabel.font = HEIGHT_FONT(18.0f);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    [self.navigationItem.titleView addSubview:titleLabel];
    
    //添加导航又边用户信息
    //初始化UINavigation左按钮
    UIButton *helloButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 80, 24)];
    [helloButton setTitle:[NSString stringWithFormat:@"你好，%@",USER_NICK_NAME] forState:UIControlStateNormal];
    helloButton.titleLabel.font = HEIGHT_FONT(13.0f);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:helloButton];
    
    //初始化UINavigation左按钮
    UIButton *naviButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 45, 24)];
    [naviButton setTitle:@"返回" forState:UIControlStateNormal];
    naviButton.titleLabel.font = HEIGHT_FONT(13.0f);
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_n.png"] forState:UIControlStateNormal];
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_p.png"] forState:UIControlStateHighlighted];
    [naviButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviButton];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavi];
    
    labelAddScroll.font = NORMAL_FONT(13.0f);
    
    NSLog(@"---jj---%@",draftDic);
    if(boolDraft == 1)
    {
        labelAddScroll.text = [draftDic objectAtIndex:5];
        toUserNameStr = [draftDic objectAtIndex:5];
        toUserIdStr = [draftDic objectAtIndex:4];
        mainTitleTextField.text = [draftDic objectAtIndex:10];
        NSString *contentStr = [draftDic objectAtIndex:11];
        contentStr = [contentStr stringByReplacingOccurrencesOfString :@"{^^^}" withString:@"\n"];
        contentStr = [contentStr stringByReplacingOccurrencesOfString :@"{###}" withString:@"\r"];
        contentTextView.text = contentStr;
    }
    else if(boolDraft == 2)
    {
        labelAddScroll.text = [draftDic objectAtIndex:5];
        toUserNameStr = [draftDic objectAtIndex:5];
        toUserIdStr = [draftDic objectAtIndex:4];
        mainTitleTextField.text = [NSString stringWithFormat:@"回复：%@",[draftDic objectAtIndex:10]];
    }
    labelAddScroll.frame = CGRectMake(2, 5, toUserNameStr.length*12+4, 20);
    receiveListSroll.contentSize = CGSizeMake(toUserNameStr.length*12+4, 30);
}

//对html设置字体以及大小
- (NSString *)convertHtmlStr:(NSString *)paramSTr
{
    NSString *resultStr = [paramSTr stringByReplacingOccurrencesOfString :@"{^^^}" withString:@"\n"];
    resultStr = [resultStr stringByReplacingOccurrencesOfString :@"{###}" withString:@"\r"];
    //建立格式
    resultStr           = [resultStr stringByAppendingString:@"</div>"];
    NSString *tempStr   = [NSString stringWithFormat:@"<div style=\"font-size:12\" style=\"color:#2c2c2c\">%@",resultStr];
    
    return tempStr;
}

//添加收件人
- (IBAction)addUserList:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
    [[SendHttpOperation shareSendHttpOperation] GetUserList:@"GetUserList.ashx"];
    [SendHttpOperation shareSendHttpOperation].getUserListDelegate = self;
}

//获取收件人回掉函数并且进入选择收件人界面
- (void)passGetUserList:(NSDictionary *)getUserListDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    SelectReceiverList *instance = [[SelectReceiverList alloc] init];
    instance.flag = 1;
    instance.selectListArr = [NSMutableArray arrayWithArray:(tempSelectArr.count ==0?@[]:tempSelectArr)];
    instance.allReceiverListArr = [NSMutableArray arrayWithArray:[[[getUserListDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"]];
    instance.delegate = self;
    [self.navigationController pushViewController:instance animated:YES];
}

//回传已经选择的收件人
//将收件人数据保存并且拼装成参数格式待使用
- (void)passList:(NSArray *)listArr
{
    NSLog(@"listArr--->%@",listArr);
    
    if(!tempSelectArr)
        tempSelectArr = [[NSArray alloc] initWithArray:listArr];
    
    NSMutableString *tempStr1 = [[NSMutableString alloc] init];
    NSMutableString *tempStr2 = [[NSMutableString alloc] init];
    for (int i = 0; i < [listArr count]; i++)
    {
        NSString *tempIdStr = [[listArr objectAtIndex:i] objectAtIndex:0];
        tempStr1.length == 0?[tempStr1 appendString:@""]:[tempStr1 appendString:@";"];
        [tempStr1 appendString:tempIdStr];
        
        NSString *tempNameStr = [[listArr objectAtIndex:i] objectAtIndex:4];
        tempStr2.length == 0?[tempStr2 appendString:@""]:[tempStr2 appendString:@";"];
        [tempStr2 appendString:tempNameStr];
    }
    
    toUserIdStr = [NSString stringWithFormat:@"%@",tempStr1];
    toUserNameStr = [NSString stringWithFormat:@"%@",tempStr2];
    NSLog(@"toUserNameStr-->%@",toUserNameStr);
    
    [self setScrollView];

}

//重新加载收件人界面
- (void)setScrollView
{
    labelAddScroll.text = toUserNameStr;
    
    labelAddScroll.frame = CGRectMake(2, 5, toUserNameStr.length*12+4, 20);
    receiveListSroll.contentSize = CGSizeMake(toUserNameStr.length*12+4, 30);
}


//触摸非编辑区域释放键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    textFieldBackImage.image = [UIImage imageNamed:@"input2_hover.png"];
    textViewBackImage.image = [UIImage imageNamed:@"input3.png"];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    textFieldBackImage.image = [UIImage imageNamed:@"input2.png"];
    
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    textFieldBackImage.image = [UIImage imageNamed:@"input2.png"];
    textViewBackImage.image = [UIImage imageNamed:@"input3_hover.png"];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    textViewBackImage.image = [UIImage imageNamed:@"input3.png"];
}

#pragma mark 发送操作
//如果收件人为空不发送
- (IBAction)writeOverAction:(UIButton *)sender
{
    if(sender.tag == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"是否将邮件存入草稿箱？"
                                                       delegate:self
                                              cancelButtonTitle:@"存入"
                                              otherButtonTitles:@"退出", nil];
        [alert show];
    }
    else
    {
        if(toUserNameStr.length != 0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
            //发送邮件
            [[SendHttpOperation shareSendHttpOperation] SendMail:@"SendMail.ashx"
                                                        mailGuid:@""
                                                    fromUserGuid:USER_OWNER_GUDID
                                                    fromDispName:USER_NICK_NAME
                                                  toUserGuidList:toUserIdStr
                                              toUserDispNameList:toUserNameStr
                                                         subject:mainTitleTextField.text.length==0?@"":mainTitleTextField.text
                                                     mailContent:contentTextView.text.length==0?@"":contentTextView.text];
            [SendHttpOperation shareSendHttpOperation].sendMailDelegate = self;
        }
        else
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"收件人不能为空，请先添加收件人！"}];
    }
}

//发送邮件回调
- (void)passSendMail:(NSDictionary *)sendMailDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    if([[[sendMailDic objectForKey:@"result"] objectForKey:@"value"] isEqualToString:@"0"])
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"邮件发送失败，请重新尝试！"}];
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"邮件已发送！"}];
        
        if(draftDic.count != 0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
            [[SendHttpOperation shareSendHttpOperation] delDraftMail:@"DelDraftMail.ashx"
                                                            mailGuid:[draftDic objectAtIndex:1]];
            [SendHttpOperation shareSendHttpOperation].delDraftMailDelegate = self;
        }
        else
        {
            [self back];
        }
    }
}

- (void)passdelDraftMail:(NSDictionary *)addDraftMailDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    [delegate backUpdata];
    [self back];
}

#pragma mark 存入草稿箱？
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        if(toUserNameStr.length!=0 && mainTitleTextField.text.length!=0 && contentTextView.text.length !=0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
            //存入草稿
            [[SendHttpOperation shareSendHttpOperation] AddDraftMail:@"AddDraftMail.ashx"
                                                             mailGuid:@""//draftDic.count!=0?[draftDic objectAtIndex:1]:@""
                                                         fromUserGuid:USER_OWNER_GUDID
                                                         fromDispName:USER_NICK_NAME
                                                       toUserGuidList:toUserIdStr
                                                   toUserDispNameList:toUserNameStr
                                                              subject:mainTitleTextField.text.length==0?@"":mainTitleTextField.text
                                                          mailContent:contentTextView.text.length==0?@"":contentTextView.text
                                                    originalMailGuid:@""]; //draftDic!= nil?[draftDic objectAtIndex:1]:@""
            [SendHttpOperation shareSendHttpOperation].addDraftMailDelegate = self;
        }
        else
           [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"保存数据不能为空！"}];
    }
    else
        [self back];
}

- (void)passAddDraftMail:(NSDictionary *)addDraftMailDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];

    if([[[addDraftMailDic objectForKey:@"result"] objectForKey:@"value"] isEqualToString:@"0"])
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"存入草稿箱失败，请重新尝试！"}];
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"已存入草稿箱！"}];
        
        if(draftDic.count != 0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
            [[SendHttpOperation shareSendHttpOperation] delDraftMail:@"DelDraftMail.ashx"
                                                            mailGuid:[draftDic objectAtIndex:1]];
            [SendHttpOperation shareSendHttpOperation].delDraftMailDelegate = self;
        }
        else
        {
            [delegate backUpdata];
            [self back];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
